<template>
	<view class="content">
		<nav-header title="商品详情">
			<template v-slot:left>
				<view v-if="from" @tap="goChat">
					<svg-icon icon="arrowLeft"></svg-icon>
				</view>
				<view v-else @tap="goBack">
					<svg-icon icon="arrowLeft"></svg-icon>
				</view>
			</template>
		</nav-header>
		<!-- <image class="img" src="/favicon.ico"></image> -->
		<up-swiper :list="info" height="376" indicator indicatorMode="line" circular></up-swiper>
		<view class="content_item">
			<scroll-view scroll-y="true" class="modal-content-scroll">
				<view class="content_top">
					<view class="price"><span>￥</span>{{
									  fen2yuan(
									    state.selectedSku.promotionPrice || state.selectedSku.price || goodsInfo.price,
									  )
									}}</view>
					<view class="inventory">{{ formatStock('exact', state.selectedSku.stock || goodsInfo.stock) }}
					</view>
				</view>
				<view class="title">{{ goodsInfo.name }}</view>
				<view class="content_title ft">
					<view class="fu_title">{{goodsInfo.introduction}}</view>
					<uni-fav :checked="checked" @click="onCollect" circle />
				</view>
				<!-- <view class="flex ft">
				<view class="flex_text">发货</view>
				<view class="fl">广东广州(48小时内发货)</view>
			</view> -->
				<!-- <view class="flex ft">
				<view class="flex_text">运费</view>
				<view class="fl">免运费(请以订单提交为准)</view>
			</view> -->
				<view class="flex_item ft" @click="selectShowDetail">
					<view class="flex">
						<view class="flex_text">选择</view>
						<view class="fl">{{goods_sku_text}}</view>
					</view>
					<svg-icon icon="arrowRight" :width="24"></svg-icon>
				</view>
				<!-- <view class="flex_item ft" @click="goshippAddress">
				<view class="flex">
					<view class="flex_text">收货地址</view>
					<view class="fl">M78星云</view>
				</view>
				<svg-icon icon="arrowRight" :width="24"></svg-icon>
			</view> -->

				<view class="content_detail ft">
					<view class="top">
						<view class="line"></view>
						<text class="title1">商品详情</text>
					</view>
					<mp-html :content="goodsInfo.description" />
				</view>
			</scroll-view>
		</view>
		<view class="content_below">
			<uni-goods-nav :options="options" :fill="true" :button-group="buttonGroup" @buttonClick="onPurchase" />
		</view>
		<up-popup :show="showDetail" type="bottom" round="10" @close="close">
			<!-- <view class="modal-content ss-flex-1">
				<scroll-view scroll-y="true" class="modal-content-scroll" @touchmove.stop>
					<view class="sku-item ss-m-b-20" v-for="property in propertyList" :key="property.id">
						<view class="label-text ss-m-b-20">{{ property.name }}</view>
						<view class="ss-flex-wrap">
							<button class="ss-reset-button spec-btn" v-for="value in property.values" :class="[
			            {
			              'ui-BG-Main-Gradient': state.currentPropertyArray[property.id] === value.id,
			            },
			            {
			              'disabled-btn': value.disabled === true,
			            },
			          ]" :key="value.id" :disabled="value.disabled === true" @tap="onSelectSku(property.id, value.id)">
								{{ value.name }}
							</button>
						</view>
					</view>
					<view class="buy-num-box ss-flex ss-col-center ss-row-between ss-m-b-40">
						<view class="label-text">购买数量</view>
						<uni-number-box :min="1" :max="state.selectedSku.stock" :step="1"
							v-model="state.selectedSku.goods_num" @change="onNumberChange($event)" />
					</view>
				</scroll-view>
			</view> -->
			<view class="bottomContent">
				<view class="modal-header ss-flex ss-col-center">
					<view class="header-left ss-m-r-30">
						<image class="sku-image" :src="state.selectedSku.picUrl || goodsInfo.picUrl"
							mode="aspectFill" />
					</view>
					<view class="header-right ss-flex-col ss-row-between ss-flex-1">
						<view class="goods-title ss-line-2">{{ goodsInfo.name }}</view>
						<view class="header-right-bottom ss-flex ss-col-center ss-row-between">
							<view class="ss-flex">
								<view class="price-text">
									{{
									  fen2yuan(
									    state.selectedSku.promotionPrice || state.selectedSku.price || goodsInfo.price,
									  )
									}}
									<text v-if="state.selectedSku.promotionType > 0">
										<text class="iconBox" v-if="state.selectedSku.promotionType === 4">
											限时优惠
										</text>
										<text class="iconBox" v-else-if="state.selectedSku.promotionType === 6">
											会员价
										</text>
										<text class="origin-price-text">
											{{ fen2yuan(state.selectedSku.price) }}
										</text>
									</text>
								</view>
							</view>
							<view class="stock-text ss-m-l-20">
								{{ formatStock('exact', state.selectedSku.stock || goodsInfo.stock) }}
							</view>
						</view>
					</view>
				</view>
				<!-- <view class="bottomContent_top">
					<view>请选择您的规格</view>
					<view @click="showDetail=false">关闭</view>
				</view> -->
				<!-- <view class="ft">
					<view class="fonttext">重量</view>
					<view class="ft">
						<radio-group @change="onTypechange">
							<label class="radio" v-for="(item,index) in weightList" :key="index">
								<radio :value="index" color="#2970FF" />{{item}}
							</label>
						</radio-group>
					</view>
				</view>
				<view class="ft">
					<view class="fonttext">类型</view>
					<view class="ft">
						<radio-group @change="onTypechange">
							<label class="radio" v-for="(item,index) in typeList" :key="index">
								<radio :value="index" color="#2970FF" />{{item}}
							</label>
						</radio-group>
					</view>
				</view> -->
				<view class="modal-content ss-flex-1">
					<scroll-view scroll-y="true" class="modal-content-scroll">
						<view class="sku-item ss-m-b-20" v-for="property in propertyList" :key="property.id">
							<view class="label-text ss-m-b-20">{{ property.name }}</view>
							<view class="ss-flex-wrap">
								<button class="ss-reset-button spec-btn" v-for="value in property.values" :class="[
				            {
				              'brand-btn': state.currentPropertyArray[property.id] === value.id,
				            },
				            {
				              'disabled-btn': value.disabled === true,
				            },
				          ]" :key="value.id" :disabled="value.disabled === true" @tap="onSelectSku(property.id, value.id)">
									{{ value.name }}
								</button>
							</view>
						</view>
						<view class="buy-num-box ss-flex ss-col-center ss-row-between ss-m-b-40">
							<view class="label-text">购买数量</view>
							<uni-number-box :min="1" :max="state.selectedSku.stock" :step="1"
								v-model="state.selectedSku.goods_num" @change="onNumberChange($event)" />
						</view>
					</scroll-view>
				</view>
				<!-- <view class="bottomContent_top ft">
					<view class="fonttext">商品数量</view>
					<uni-number-box :value="numberValue" @change="change" />
				</view> -->
				<view style="margin-top: 50rpx;">
					<button class="confirm" type="primary" @click="showDetail=false">确认</button>
				</view>
			</view>
		</up-popup>
		<!-- <SelectSku :show="showDetail"></SelectSku> -->
	</view>
</template>

<script>
	// import SelectSku from "./components/s-select-sku"
	export default {
		components: {
			// SelectSku
		},
		data() {
			return {
				showDetail: false,
				options: [{
					icon: 'headphones',
					text: '客服'
				}, {
					icon: 'redo',
					text: '分享',

				}, {
					icon: 'cart',
					text: '购物车',
				}],
				buttonGroup: [{
						text: '加入购物车',
						backgroundColor: '#17B26A',
						color: '#fff'
					},
					{
						text: '立即购买',
						backgroundColor: '#2970FF',
						color: '#fff'
					}
				],
				goodsInfo: {},
				propertyList: [],
				state: {
					selectedSku: {}, // 选中的 SKU
					currentPropertyArray: [],
				},
				checked: false,
				weightList: ['1kg', '2kg', '3kg'],
				typeList: ['oppo', '小米', '华为', '荣耀'],
				numberValue: 0,
				swiperDotIndex: 0,
				info: [],
				spuId: null,
				from:null
			}
		},
		computed: {
			skuList() {
				let skuPrices = this.goodsInfo.skus;
				for (let price of skuPrices) {
					price.value_id_array = price.properties.map((item) => item.valueId);
				}
				return skuPrices;
			},
			goods_sku_text() {
				if (!this.state.selectedSku.id) {
					return '请选择商品规格';
				}
				let str = '';
				this.state.selectedSku.properties.forEach(property => {
					str += property.propertyName + ':' + property.valueName + ' ';
				});
				return str.trim();
			}
		},
		watch: {
			'state.selectedSku': {
				handler(newVal) {
					this.state.selectedSku = newVal
				},
				immediate: true,
				deep: true, // 如果 selectedSku 是对象/数组
			}
		},
		methods: {
			goChat() {
				uni.navigateTo({
					url: "/pageSubOne/mine/shoppcollect"
				})
			},
			goBack() {
				uni.navigateBack()
			},
			fen2yuan(price) {
				return (price / 100.0).toFixed(2);
			},
			formatStock(type, num) {
				return this.formatNum('库存', type, num);
			},
			formatNum(prefix, type, num) {
				num = num || 0;
				// 情况一：精确数值
				if (type === 'exact') {
					return prefix + num;
				}
				// 情况二：小于等于 10
				if (num < 10) {
					return `${prefix}≤10`;
				}
				// 情况三：大于 10，除第一位外，其它位都显示为0
				// 例如：100  - 199  显示为 100+
				//      9000 - 9999 显示为 9000+
				const numStr = num.toString();
				const first = numStr[0];
				const other = '0'.repeat(numStr.length - 1);
				return `${prefix}${first}${other}+`;
			},
			close() {
				this.showDetail = false
			},
			convertProductPropertyList(skus) {
				let result = [];
				for (const sku of skus) {
					if (!sku.properties) {
						continue;
					}
					for (const property of sku.properties) {
						// ① 先处理属性
						let resultProperty = result.find((item) => item.id === property.propertyId);
						if (!resultProperty) {
							resultProperty = {
								id: property.propertyId,
								name: property.propertyName,
								values: [],
							};
							result.push(resultProperty);
						}
						// ② 再处理属性值
						let resultValue = resultProperty.values.find((item) => item.id === property.valueId);
						if (!resultValue) {
							resultProperty.values.push({
								id: property.valueId,
								name: property.valueName,
							});
						}
					}
				}
				return result;
			},
			// 选择规格
			onSelectSku(propertyId, valueId) {
				// 清空已选择
				let isChecked = true; // 选中 or 取消选中
				if (
					this.state.currentPropertyArray[propertyId] !== undefined &&
					this.state.currentPropertyArray[propertyId] === valueId
				) {
					// 点击已被选中的，删除并填充 ''
					isChecked = false;
					this.state.currentPropertyArray.splice(propertyId, 1, '');
				} else {
					// 选中
					this.state.currentPropertyArray[propertyId] = valueId;
				}

				// 选中的 property 大类
				let choosePropertyId = [];
				this.state.currentPropertyArray.forEach((currentPropertyId) => {
					if (currentPropertyId !== '') {
						// currentPropertyId 为空是反选 填充的
						choosePropertyId.push(currentPropertyId);
					}
				});

				// 当前所选 property 下，所有可以选择的 SKU 们
				let newSkuList = this.getCanUseSkuList();

				// 判断所有 property 大类是否选择完成
				if (choosePropertyId.length === this.propertyList.length && newSkuList.length) {
					newSkuList[0].goods_num = this.state.selectedSku.goods_num || 1;
					this.state.selectedSku = newSkuList[0];
				} else {
					this.state.selectedSku = {};
				}

				// 改变 property 禁用状态
				this.changeDisabled(isChecked, propertyId, valueId);
			},
			// 改变禁用状态：计算每个 property 属性值的按钮，是否禁用
			changeDisabled(isChecked = false, propertyId = 0, valueId = 0) {
				let newSkus = []; // 所有可以选择的 sku 数组
				if (isChecked) {
					// 情况一：选中 property
					// 获得当前点击选中 property 的、所有可用 SKU
					for (let price of this.skuList) {
						if (price.stock <= 0) {
							continue;
						}
						if (price.value_id_array.indexOf(valueId) >= 0) {
							newSkus.push(price);
						}
					}
				} else {
					// 情况二：取消选中 property
					// 当前所选 property 下，所有可以选择的 SKU
					newSkus = this.getCanUseSkuList();
				}

				// 所有存在并且有库存未选择的 SKU 的 value 属性值 id
				let noChooseValueIds = [];
				for (let price of newSkus) {
					noChooseValueIds = noChooseValueIds.concat(price.value_id_array);
				}
				noChooseValueIds = Array.from(new Set(noChooseValueIds)); // 去重

				if (isChecked) {
					// 去除当前选中的 value 属性值 id
					let index = noChooseValueIds.indexOf(valueId);
					noChooseValueIds.splice(index, 1);
				} else {
					// 循环去除当前已选择的 value 属性值 id
					this.state.currentPropertyArray.forEach((currentPropertyId) => {
						if (currentPropertyId.toString() !== '') {
							return;
						}
						// currentPropertyId 为空是反选 填充的
						let index = noChooseValueIds.indexOf(currentPropertyId);
						if (index >= 0) {
							// currentPropertyId 存在于 noChooseValueIds
							noChooseValueIds.splice(index, 1);
						}
					});
				}

				// 当前已选择的 property 数组
				let choosePropertyIds = [];
				if (!isChecked) {
					// 当前已选择的 property
					this.state.currentPropertyArray.forEach((currentPropertyId, currentValueId) => {
						if (currentPropertyId !== '') {
							// currentPropertyId 为空是反选 填充的
							choosePropertyIds.push(currentValueId);
						}
					});
				} else {
					// 当前点击选择的 property
					choosePropertyIds = [propertyId];
				}

				for (let propertyIndex in this.propertyList) {
					// 当前点击的 property、或者取消选择时候，已选中的 property 不进行处理
					if (choosePropertyIds.indexOf(this.propertyList[propertyIndex]['id']) >= 0) {
						continue;
					}
					// 如果当前 property id 不存在于有库存的 SKU 中，则禁用
					for (let valueIndex in this.propertyList[propertyIndex]['values']) {
						this.propertyList[propertyIndex]['values'][valueIndex]['disabled'] =
							noChooseValueIds.indexOf(this.propertyList[propertyIndex]['values'][valueIndex]['id']) <
							0; // true 禁用 or false 不禁用
					}
				}
			},
			// 当前所选属性下，获取所有有库存的 SKU 们
			getCanUseSkuList() {
				let newSkus = [];
				for (let sku of this.skuList) {
					if (sku.stock <= 0) {
						continue;
					}
					let isOk = true;
					this.state.currentPropertyArray.forEach((propertyId) => {
						// propertyId 不为空，并且，这个 条 sku 没有被选中，则排除
						if (propertyId.toString() !== '' && sku.value_id_array.indexOf(propertyId) < 0) {
							isOk = false;
						}
					});
					if (isOk) {
						newSkus.push(sku);
					}
				}
				return newSkus;
			},
			// 输入框改变数量
			onNumberChange(e) {
				if (e === 0) return;
				if (this.state.selectedSku.goods_num === e) return;
				this.state.selectedSku.goods_num = e;
			},
			onTypechange() {},
			change() {},
			selectShowDetail() {
				this.showDetail = true
			},
			onCollect() {
				// this.checked = !this.checked
				if (this.checked) {
					this.$http({
						url: '/product/favorite/delete',
						method: 'DELETE',
						data: {
							spuId: this.spuId
						}
					}).then(res => {
						uni.showToast({
							title:"取消收藏成功",
							icon:"none"
						})
						this.checked = false
					})
				} else {
					this.$http({
						url: "/product/favorite/create",
						method: 'POST',
						data: {
							spuId: this.spuId
						}
					}).then(res => {
						uni.showToast({
							title:"收藏成功",
							icon:"none"
						})
						this.checked = true
					})
				}

			},
			onPurchase(e) {
				if (e.index == 0) {
					uni.showToast({
						title: "购物车功能未开放",
						icon: 'none'
					})
				} else {
					uni.showToast({
						title: "购买功能",
						icon: 'none'
					})
				}

			},
			goshippAddress() {
				uni.navigateTo({
					url: "/pageSubOne/mine/mine-shippAddress"
				})
			},
			getCollect(id) {
				this.$http({
					url: '/product/favorite/exits?spuId=' + id,
					method: 'GET',
				}).then(res => {
					this.checked = res
				})
			},
			getRules(id) {
				this.$http({
					url: "/product/spu/get-detail?id=" + id,
					method: "GET"
				}).then(res => {
					this.goodsInfo = res
					this.propertyList = this.convertProductPropertyList(res.skus)
					this.info = res.sliderPicUrls
				})
			}
		},
		onLoad(options) {
			this.spuId = options.id
			this.from=options.from
			this.getRules(options.id)
			this.getCollect(options.id)
		}
	}
</script>

<style lang="scss" scoped>
	.content {

		.img {
			width: 100%;
			//border: 1px solid red;
		}

		.content_item {
			padding: 20rpx;
			padding-bottom: 120rpx;

			.content_top {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.price {
					color: #E63232;
					font-size: 34rpx;
					font-weight: bold;

					span {
						font-size: 16rpx;
					}
				}

				.inventory {
					color: #333333;
					font-size: 26rpx;
				}
			}

			.content_detail {
				display: flex;
				// align-items: center;
				flex-direction: column;
				gap: 20rpx;
				margin-top: 50rpx;

				.top {
					display: flex;
					align-items: center;
					gap: 20rpx;
				}

				.title1 {
					font-size: 32rpx;
					font-weight: 999;
				}

				.line {
					margin-top: 5rpx;
				}

				.line::after {
					content: "";
					display: inline-block;
					/* 关键！ */
					width: 6rpx;
					height: 32rpx;
					/* 调整高度 */
					// background: linear-gradient(90deg, #d10019 0%, rgba(209, 0, 25, 0.6) 100%);
					background-color: red;
					border-radius: 1rpx;
				}
			}

			.title {
				color: #1A1A1A;
				font-size: 36rpx;
				margin-top: 10rpx;
				font-weight: bold;
			}

			.content_title {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.fu_title {
					color: #999999;
					font-size: 26rpx;
				}
			}

			.flex_item {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}

			.flex {
				display: flex;

				.flex_text {
					color: #999999;
					font-size: 30rpx;
				}

				.fl {
					font-size: 30rpx;
					margin-left: 30rpx;
				}
			}
		}

		.content_below {
			display: flex;
			flex-direction: column;
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
		}

		.bottomContent {
			padding: 20rpx;
			border-radius: 10rpx 10rpx 0 0;

			.modal-header {
				display: flex;
				position: relative;
				padding: 80rpx 20rpx 40rpx;

				.sku-image {
					width: 160rpx;
					height: 160rpx;
					border-radius: 10rpx;
				}

				.header-right {
					height: 160rpx;
				}

				.close-icon {
					position: absolute;
					top: 10rpx;
					right: 20rpx;
					font-size: 46rpx;
					opacity: 0.2;
				}

				.goods-title {
					font-size: 28rpx;
					font-weight: 500;
					line-height: 42rpx;
				}

				.score-img {
					width: 36rpx;
					height: 36rpx;
					margin: 0 4rpx;
				}

				.score-text {
					font-size: 30rpx;
					font-weight: 500;
					color: $error-500;
					font-family: OPPOSANS;
				}

				.price-text {
					font-size: 30rpx;
					font-weight: 500;
					color: $error-500;
					font-family: OPPOSANS;

					&::before {
						content: '￥';
						font-size: 30rpx;
						font-weight: 500;
						color: $error-500;
					}
				}

				.stock-text {
					font-size: 26rpx;
					color: #999999;
				}
			}

			.bottomContent_top {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}

			.radio {
				padding: 10rpx;
			}

			.fonttext {
				font-size: 20rpx;
				color: #333333;
			}
		}

		.ft {
			margin-top: 30rpx;
		}

		.modal-content {
			padding: 0 20rpx;

			.modal-content-scroll {
				max-height: 600rpx;

				.label-text {
					font-size: 26rpx;
					font-weight: 500;
				}

				.buy-num-box {
					margin-top: 20rpx;
					display: flex;
					justify-content: space-between;
					// height: 100rpx;
				}

				.ss-flex-wrap {
					display: flex;
					padding: 10rpx;

					.spec-btn {
						height: 60rpx;
						min-width: 100rpx;
						padding: 0 30rpx;
						background: #f4f4f4;
						border-radius: 30rpx;
						color: #434343;
						font-size: 26rpx;
						margin-left: 50rpx;
						margin-bottom: 10rpx;
						text-align: center;
					}

					.disabled-btn {
						font-weight: 400;
						color: #c6c6c6;
						background: #f8f8f8;
					}

					.brand-btn {
						font-weight: 400;
						background-color: $brand-500 !important;
						color: white !important;
					}
				}
			}
		}

		.confirm {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 30rpx;
			border-radius: 50rpx;
			background-color: $brand-500;
			color: white;
		}
	}
</style>